Q.Node.prototype.type = "Node";
Q.Text.prototype.type = "Text";
Q.Group.prototype.type = "Group";
Q.Edge.prototype.type = "Edge";

let graph;
let globaltopoNodes = [];
let hasTimeEdge = {};
let relationsNum = {};
let locationHref = [];
let chartInitNum = {
  startPercent: 50,
  endPercent: 80,
};


$(function () {
  Q.addCSSRule(".maximize", "margin: 0px !important;position: fixed !important;top: 0px;bottom: 0px;right: 0px;left: 0px;z-index: 1030;height: auto !important; width: auto !important;");
  graph = new Q.Graph("canvas");

  let styles = {};
  styles[Q.Styles.SELECTION_COLOR] = "#0F0";
  graph.styles = styles;

  locationHref = (function () {
    const url = window.location.href;
    return url.substring(url.lastIndexOf('ids=') + 4, url.length).split(',');
  })();
  locationHref = Object.assign([], locationHref);

  // graph.originAtCenter = false;
  // graph.editable = true;

  graph.onElementCreated = function (element, evt) {
    if (element instanceof Q.Edge) {
      let v = prompt("连线粗度");
      v = parseInt(v);
      if (v) {
        element.setStyle(Q.Styles.EDGE_WIDTH, v);
      } else {
        graph.removeElement(element);
      }
      if (element.edgeType && element.edgeType !== Q.Consts.EDGE_TYPE_DEFAULT) {
        element.setStyle(Q.Styles.EDGE_BUNDLE, false);
      }
      element.name = '';
      return;
    }
    if (element instanceof Q.Text) {
      element.setStyle(Q.Styles.LABEL_BACKGROUND_COLOR, "#2898E0");
      element.setStyle(Q.Styles.LABEL_COLOR, "#FFF");
      element.setStyle(Q.Styles.LABEL_FONT_SIZE, 20);
      element.setStyle(Q.Styles.LABEL_PADDING, new Q.Insets(3, 5));
      return;
    }
    if (element instanceof Q.Node) {
      let rNode = graph.graphModel.get(0);
      graph.createEdge(rNode, element);
    }
  };

  graph.onLabelEdit = function (element, label, text, elementUI) {
    if (!text) {
      return false;
    }
    element.name = text;
    //此处调用后台保存
  };

  initToolbar();
  // initToolbox();
  getDataBase(locationHref, true, '1');

  //监听面板调整大小事件，同步graph大小
  $('#center_panel').panel({
    onResize: function (w, h) {
      graph.updateViewport();
    }
  });

  $('#canvas').graphEditor(graph, {
    saveService: 'save',
    callback: function (editor) {
      let graph = editor.graph;
      graph.addCustomInteraction({
        onclick: function(evt, graph) {
          let ui = graph.getUIByMouseEvent(evt);
          if (!ui) {
            graph.cursor = null;
            return;
          }
          graph.cursor = "pointer";
        }
      });
    }
  });
});


function timerShaft(relations) {
  // console.log(relations);
  // 时间轴属性

  let endDate = new Date();
  let startDate = new Date();
  startDate.setFullYear(new Date().getFullYear() - 10);
  let xData = [];
  let yData = [];
  for (let i = startDate; i <= endDate; i.setDate(i.getDate() + 1)) {
    const temp = echarts.format.formatTime('yyyy-MM-dd', i);
    xData.push(temp);
    yData.push(0);
  }
  for (const key in hasTimeEdge) {
    const index = xData.indexOf(key);
    if (index !== -1) {
      // console.log(index);
      yData[index] = hasTimeEdge[key].length;
    }
  }

  // console.log(yData);
  //时间轴
  let timelineChart = echarts.init(document.getElementById('timeline'));
  let option = {
    backgroundColor: '#0f2b32',
    xAxis: {
      type: 'category',
      splitLine: {
        show: false
      },
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#d5d6d8'
        }
      },
      data: xData
    },
    yAxis: {
      show: false,
      type: 'value',
      max: 'dataMax',
      splitLine: {
        show: false
      }
    },
    dataZoom: [
      {
        type: 'slider',
        bottom: 0,
        start: chartInitNum.startPercent,
        end: chartInitNum.endPercent,
        // xAxisIndex: 0,
        filterMode: 'empty'
      },
      {
        type: 'inside',
        xAxisIndex: 0,
        filterMode: 'empty'
      }
    ],
    series: [
      {
        type: 'bar',
        itemStyle: { color: '#44b8df'},
        normal: {
          textStyle: {
            color: 'yellow'
          }
        },
        data: yData
      }
    ]
  };

  // 使用刚指定的配置项和数据显示图表。

  let adasdas = [{x: '123', y: '124'},{x: 12, y: 5676547}];

  timelineChart.setOption(option);
  timelineChart.off('datazoom');
  timelineChart.on('datazoom',(params)=> {
    //params里面有什么，可以打印出来看一下就明白
    //可以通过params获取缩放的起止百分比，但是鼠标滚轮和伸缩条拖动触发的params格式不同，所以用另一种方法
    //获得图表数据数组下标
    let startValue = timelineChart.getModel().option.dataZoom[0].startValue;
    let endValue = timelineChart.getModel().option.dataZoom[0].endValue;
    //获得起止位置百分比
    chartInitNum.startPercent = timelineChart.getModel().option.dataZoom[0].start;
    chartInitNum.endPercent = timelineChart.getModel().option.dataZoom[0].end;

    const startTime = new Date(xData[startValue]),
      endTime = new Date(xData[endValue]);

    if (hasTimeEdge) {
      for (const edge in hasTimeEdge) {
        if (hasTimeEdge[edge][0].info['开始时间'] === undefined) return;
        // const edgeTime = new Date(hasTimeEdge[edge][0].info['开始时间'].toString().replace('/\-/g',"v"));
        const edgeTime = new Date(hasTimeEdge[edge][0].info['开始时间']).setHours(0, 0, 0, 0);
        const edgePoint = hasTimeEdge[edge][0];

        if (edgeTime > startTime && edgeTime <= endTime ) {
          clearInterval(hasTimeEdge[edge][1]);
          hasTimeEdge[edge] = hasTimeEdge[edge].slice(0,1);
          edgePoint.setStyle(Q.Styles.EDGE_LINE_DASH, [2, 1]);
          edgePoint.setStyle(Q.Styles.ARROW_TO_LINE_DASH, [2, 1]);
          edgePoint.offset = 0;

          const edgeInterval = setInterval(function () {
            edgePoint.offset++;
            edgePoint.offset = edgePoint.offset % 20.5;
            const speed = -0.3 - 0.03 * (20 - edgePoint.offset);
            edgePoint.setStyle(Q.Styles.ARROW_TO_OFFSET, speed);
          }, 100);
          hasTimeEdge[edge].push(edgeInterval);
        } else {
          clearInterval(hasTimeEdge[edge][1]);
          edgePoint.setStyle(Q.Styles.EDGE_LINE_DASH, null);
          edgePoint.setStyle(Q.Styles.ARROW_TO_LINE_DASH, null);
          edgePoint.setStyle(Q.Styles.ARROW_TO_OFFSET, 0);
        }
      }
    }
  });
  $("#timeline").panel({
    onResize: function () {
      timelineChart.resize();
    }
  });
};

function ensureVisible(node) {
  let bounds = graph.getUIBounds(node);
  let viewportBounds = graph.viewportBounds;
  if (!viewportBounds.contains(bounds)) {
    graph.sendToTop(node);
    graph.centerTo(node.x, node.y);
  }
}

function setInteractionMode(evt, info) {
  graph.interactionMode = info.value;
  currentInteractionMode = info.value;

  if (info.value == Q.Consts.INTERACTION_MODE_CREATE_EDGE) {
    graph.edgeUIClass = info.edgeUIClass;
    graph.edgeType = info.edgeType;
  }

  $img = $(evt.target);
  $img.parent().siblings().removeClass('active');
  $img.siblings().removeClass('active');
  $img.parent().addClass('active');
  $img.addClass('active');
}

function initToolbar() {
  let toolbar = document.getElementById("toolbar");
  let buttons = {
    interactionModes: [{name: "默认模式", value: Q.Consts.INTERACTION_MODE_DEFAULT, selected: true, icon: 'images/default_icon.png', action: setInteractionMode},
      {name: '框选模式', value: Q.Consts.INTERACTION_MODE_SELECTION, icon: 'images/rectangle_selection_icon.png', action: setInteractionMode},
      {name: '浏览模式', value: Q.Consts.INTERACTION_MODE_VIEW, icon: 'images/pan_icon.png', action: setInteractionMode}],
    zoom: [{
      name: "放大", icon: "images/zoomin_icon.png", action: function () {
        graph.zoomIn()
      }
    },
      {
        name: "缩小", icon: "images/zoomout_icon.png", action: function () {
          graph.zoomOut()
        }
      },
      {
        name: "1:1", action: function () {
          graph.scale = 1;
        }
      },
      {
        name: '纵览', icon: 'images/overview_icon.png', action: function () {
          this.zoomToOverview()
        }
      }
      // {
      //     name: '最大化', icon: 'images/fullscreen_icon.png', action: function () {
      //         if ($("#graph_panel").hasClass("maximize")) {
      //             $("#graph_panel").removeClass("maximize")
      //         } else {
      //             $("#graph_panel").addClass("maximize")
      //         }
      //         graph.updateViewport();
      //     }
      // }
    ],
    layout: [
      {
        name: '圆型', action: function (evt, info) {
          layout('balloon');
        }
      },
      {
        name: '树型', action: function (evt, info) {
          layout('tree');
        }
      }
    ],
    find: {
      name: '<img src="images/search.png"/>', class: 'btn_bgc', type: "input", action: function (evt, info) {
        let name = info.input.value;
        if (!name) {
          return;
        }
        graph.forEach(function (e) {
          if (e instanceof Q.Node && (name == e.name || (e.info && e.info.name == name))) {
            graph.setSelection(e);
            ensureVisible(e);
            return false;
          }
        }, graph);
      }
    }
  };
  createToolBar(buttons, toolbar, graph, false, false);

}

function initToolbox() {
  let toolbox = document.getElementById("toolbox");

  createToolBar({
    a: [
      {name: '普通连线', value: Q.Consts.INTERACTION_MODE_CREATE_EDGE, icon: 'images/edge_icon.png', action: setInteractionMode},
      {name: '正交直线', value: Q.Consts.INTERACTION_MODE_CREATE_EDGE, icon: 'images/edge_orthogonal_icon.png', action: setInteractionMode, edgeType: Q.Consts.EDGE_TYPE_ORTHOGONAL_HORIZONTAL}]
  }, toolbox, graph, "btn-group-vertical", false);

  let text = createDNDImage(toolbox, "images/text_icon.png", "指令", {type: "Text", label: "指令"});
  text.style.marginLeft = '6px';
  // createDNDImage(toolbox, "images/node_icon.png", "节点", {type: "Node", label: "节点", image: "Q.Graphs.node"});
}


function getDataBase(attrs, judge, num) {
  if (graph.graphModel.size() > 200) {
    alert('炸开节点过多');
    return;
  }

  $.ajax({
    url: '/api/systemRelevance/multilevelBlowOpen',
    // url: 'http://192.168.1.132/api/systemRelevance/multilevelBlowOpen',
    type: 'post',
    headers: {'token': sessionStorage.token},
    data: JSON.stringify({ids: attrs, target: num}),
    contentType: 'application/json; charset=utf-8',
    success: function (res) {
      let topoNodes = res.node;
      const relations = res.relationship;

      if (judge) {
        topoNodes = [];
        for (const i of res['node']) {
          if (attrs.indexOf(i['编号'].toString()) > -1) {
            topoNodes.push(i);
          }
        }
      }
      initTopology(topoNodes, relations);

      timerShaft(relations);
    },
    error: function (res) {
      window.location.href = '/login';
    }
  });
}

function getTreeIcon(d) {
  return d instanceof Q.Edge ? "edge_icon" : "node_icon";
}

function initTopology(topoNodes, topoRelations) {
  for (item of topoNodes) {
    const nodeObj = graph.graphModel.getById(item['编号']);
    if (!nodeObj && item['名称']) {
      let qNode = null;
      qNode = new Q.Node(item['名称']);
      qNode.location = new Q.Point(item.x, item.y);
      qNode.setStyle(Q.Styles.LABEL_COLOR, "#FFF");
      qNode.setStyle(Q.Styles.LABEL_FONT_SIZE, 18);
      qNode.id = item['编号'];
      qNode.attr = [];
      qNode.topoRelations = [];
      qNode.attr = item;
      if (qNode.attr['类型'] !== []) {
        qNode.attr['类型'] = (function () {
          let attrType = ['', 0];
          for (const i of qNode.attr['类型']) {
            const key = Object.keys(i);
            const value = Object.values(i);
            if (attrType[1] < value[0]) {
              attrType[0] = key[0];
            }
          }
          return attrType[0];
        })();
      }
      let urlImg = '../perception/images/content_menu/';
      let imgMap = {
        '机场': 'content_menu.png', '舰艇': 'content_menu15.png', '两栖攻击舰': 'content_menu15.png', '驱逐舰': 'content_menu15.png', '巡洋舰': 'content_menu15.png', '海上作战力量': 'content_menu15.png', '动目标': 'content_menu23.png', '军事基地': 'content_menu2.png', '海军基地': 'content_menu2.png', '指挥所': 'content_menu5.png', '港口': 'content_menu6.png', '医院': 'content_menu12.png', '雷达站': 'content_menu2.png', '导弹部队': 'content_menu9.png', '发电站': 'content_menu11.png', '铁路线': 'content_menu19.png', '车站': 'content_menu20.png', '高速公路': 'content_menu19.png', '国际组织': 'content_menu18.png', '学校': 'content_menu21.png', '状态': 'content_menu23.png', '预警': 'content_menu16.png', '陆基': 'content_menu17.png'
      };
      qNode.image = imgMap[qNode.attr['类型']] !== undefined ? `${urlImg}${imgMap[qNode.attr['类型']]}` : `${urlImg}content_menu23.png`;

      if (qNode.attr['类型'] === '') delete qNode.attr['类型'];
      for (const item of topoRelations) {
        if (qNode.attr['编号'] === item['编号']) {
          qNode.attr['关系属性'] = item['关系类型'];
        }
      }
      graph.graphModel.add(qNode);
    }
  }

  // 绘制关系线
  let i = 0;
  for (; i < topoRelations.length; i++) {
      let relation = topoRelations[i];
      let nodeFrom = relation['from'];
      let nodeTo = relation['to'];
      let code = relation['编号'];
      if (nodeFrom && nodeTo) {
        let nodeFromObj = graph.graphModel.getById(nodeFrom);
        let nodeToObj = graph.graphModel.getById(nodeTo);
        let relat = relationsNum[nodeFrom + '-' + nodeTo];


        if (relat !== undefined && relat.indexOf(code) === -1) {
          if (relat.indexOf(code) === -1) {
            relat.push(code);
            let edge = graph.graphModel.getById(relat[0]);

            if (relat.length > 8) {
              edge.setStyle(Q.Styles.EDGE_WIDTH, 8);
            } else if (relat.length > 3) {
              edge.setStyle(Q.Styles.EDGE_WIDTH, 5);
            } else if (relat.length > 1) {
              edge.setStyle(Q.Styles.EDGE_WIDTH, 3);
            }
          }
        } else if (relat === undefined) {
          relationsNum[nodeFrom + '-' + nodeTo] = [code];

          let edge = new Q.Edge(nodeFromObj, nodeToObj);

          edge.id = code;
          edge.info = relation;
          edge.setStyle(Q.Styles.EDGE_COLOR, "#FFF");
          graph.graphModel.add(edge);

          if (relation['开始时间'] !== undefined && relation['开始时间'] !== '') {
            const starTime = relation['开始时间'];
            const time = dateFtt("yyyy-MM-dd", new Date(starTime));

            if (hasTimeEdge[time] === undefined) {
              hasTimeEdge[time] = [edge];
            } else {
              hasTimeEdge[time].push(edge);
            }
          }
        }
      }
  }

  graph.callLater(function () {
    if (graph.graphModel.size() < 3) {
      layout('tree');
    } else {
      layout('balloon');
    }
  });
}

function connectNewNode(from, to, nodes) {
  let preNode = null;
  for(let i = 0; i < nodes.length; i++) {
    let node = nodes[i];
    let qNode = new Q.Node(node.name);
    let qEdge = null;

    qNode.location = new Q.Point(node.x, node.y);
    qNode.setStyle(Q.Styles.LABEL_COLOR, "#FFF");
    graph.graphModel.add(qNode);

    if(to) {
      if(nodes.length === 0) {
        qEdge = graph.createEdge(from, qNode);
        qEdge.setStyle(Q.Styles.EDGE_COLOR, "#FFF");
        qEdge = graph.createEdge(qNode, to);
      } else {
        if(i === 0) {
          qEdge = graph.createEdge(from, qNode);
          preNode = qNode;
        } else if(i === nodes.length - 1) {
          qEdge = graph.createEdge(preNode, qNode);
          qEdge.setStyle(Q.Styles.EDGE_COLOR, "#FFF");
          qEdge = graph.createEdge(qNode, to);
        } else {
          qEdge = graph.createEdge(preNode, qNode);
          preNode = qNode;
        }
      }
    } else {
      qEdge = graph.createEdge(from, qNode);
    }
    qEdge.setStyle(Q.Styles.EDGE_COLOR, "#FFF");
  }
}

function layout(type) {
  let layouter = null;
  switch (type) {
    case 'tree': {
      layouter = new Q.TreeLayouter(graph);
      break;
    }
    case 'balloon': {
      layouter = new Q.SpringLayouter(graph);
      layouter.repulsion = 180;
      layouter.elastic = 1;
      break;
    }
  }

  layouter.doLayout({
    byAnimate: true,
    callback: function () {
      graph.moveToCenter();
      // graph.zoomToOverview();
    }
  });
}

function dateFtt(fmt,date) {
  var o = {
    "M+" : date.getMonth()+1,                 //月份
    "d+" : date.getDate(),                    //日
    "h+" : date.getHours(),                   //小时
    "m+" : date.getMinutes(),                 //分
    "s+" : date.getSeconds(),                 //秒
    "q+" : Math.floor((date.getMonth()+3)/3), //季度
    "S"  : date.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}